<!---->
<template>
  <div class="issue">
    <h3>发布文章</h3>
    <div class="wrap">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="title">
          <el-input
            v-model="ruleForm.title"
            placeholder="请输入文章标题（5-50个字）"
            maxlength="50"
            minlength="5"
            show-word-limit
          ></el-input>
        </el-form-item>
        <div id="vditor"></div>
        <div class="sel">
          <el-select v-model="ruleForm.category" placeholder="请选择文章分类">
            <el-option
              v-for="item in category"
              :key="item.categoryname"
              :label="item.categoryname"
              :value="item.categoryname"
            >
            </el-option>
          </el-select>
        </div>
        <div style="margin: 20px 0">
          <el-form-item label="文章封面">
            <el-upload
              class="avatar-uploader"
              action="api/UploadImg"
              :multiple="false"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>
        <div class="btn">
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >提交</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import<组件名字> from '<组件路径>';
import Vditor from "vditor";
import "vditor/dist/index.css";
export default {
  //import引入的组件需要注入对象中才能用
  components: {},
  data() {
    return {
      dialogImageUrl: "",
      imageUrl: '',
      dialogVisible: false,
      fileList: [],
      category: [
        { value: "psd", id: "1" },
        { value: "psd", id: "2" },
        { value: "psd", id: "3" },
        { value: "psd", id: "4" },
        { value: "psd", id: "5" },
      ],
      titlenum: "0",
      contentEditor: "",
      input: "",
      ruleForm: {
        title: "", //标题
        category: "", //类别
        content: "", //内容
      },
      rules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            min: 5,
            max: 50,
            message: "长度在 5 - 50 个字符",
            trigger: "blur",
          },
        ],
        category: [
          { required: true, message: "请选择文章分类", trigger: "change" },
        ],
      },
      postData: {
        pageNo: "1",
        pageSize: "5",
        categroy: "allin",
      },
    };
  },
  //监听属性 类似于data概念
  computed: {
    user(){
      if(sessionStorage.getItem("user")){
        this.$store.commit("setUserObj",JSON.parse(sessionStorage.getItem("user")))
      }else{
        this.$store.commit("setUserObj",null)
      }
      return this.$store.state.userObj
    }
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //提交添加博客
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          if (
            this.contentEditor.getValue().length == 1 ||
            this.contentEditor.getValue() == null ||
            this.contentEditor.getValue() == ""
          ) {
            alert("文章内容不可为空");
            return false;
          }
          this.ruleForm.content = this.contentEditor.getHTML();
          this.ruleForm.author = this.user.nickname;
          this.ruleForm.userid = this.user.id;
          this.API.addBlog(this.ruleForm).then((res) => {
            if (res.message.code == 200) {
              this.contentEditor.setValue("");
              this.ruleForm.title = "";
              this.ruleForm.category = "";
              this.imgPath = ''
              this.$message({
                message: res.message.msg,
                type: "success",
              });
            } else {
              this.$message({
                message: res.message.msg,
                type: "error",
              });
            }
          });
          console.log("数据", this.ruleForm);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(ruleForm) {
      this.$refs[ruleForm].resetFields();
    },
    getList() {
      this.API.getCategoryList(this.postData).then((res) => {
        if (res.message.code == 200) {
          this.category = res.data.pageData || [];
          console.log("获取列表成功");
        } else {
          console.log("获取列表失败");
        }
      });
    },
    //删除已上传文件
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      console.log("file", file);
      this.dialogImageUrl = file.response.data; //拿到路径放大图片
      this.dialogVisible = true;
    },
    //获取图片路径
    handleAvatarSuccess(res, file) {
      console.log("shishen",file)
        this.ruleForm.imgPath = file.response.data;
        this.imageUrl = file.response.data
        console.log("dd",this.ruleForm.imgPath)
      },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期-挂载完成（可以访问DOM元素）
  mounted() {
    this.contentEditor = new Vditor("vditor", {
      height: 400,
      minHeight: 300,
      placeholder: "请输入文章内容",
      toolbarConfig: {
        pin: true,
      },
      counter: {
        enable: true,
      },
      cache: {
        enable: false,
      },
      // 文件上传配置
      // upload: {
      //   accept: "image/*,.mp3, .wav, .rar",
      //   token: "test",
      //   url: "/api/upload/editor",
      //   linkToImgUrl: "/api/upload/fetch",
      //   filename(name) {
      //     return name
      //       .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
      //       .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
      //       .replace("/\\s/g", "");
      //   },
      // },
      after: () => {
        this.contentEditor.setValue(""); //数据回显
      },
    });
    this.getList();
  },
  beforeCreate() {}, //生命周期-创建之前
  beforeMount() {}, //生命周期-挂载之前
  beforeUpdate() {}, //生命周期-更新之前
  updated() {}, //生命周期-更新之后
  beforeDestroy() {}, //生命周期-销毁之前
  destroyed() {}, //生命周期-销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个会输会触发
};
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style lang='less' scoped>

//@import url(); 引入公共css类
.el-button {
  width: 115px;
}
.el-select {
  width: 100%;
}
.issue {
  width: 1000px;
  margin: 0 auto;
  height: auto;
  padding-bottom: 94px;
  h3 {
    z-index: 99;
  }
  .wrap {
    position: relative;
    // margin: 20px 0;
    .btn {
      position: fixed;
      bottom: 0;
      background-color: #fff;
      left: 0;
      right: 0;
      border-top: 1px solid #e8e8e8;
      z-index: 8;
      height: 70px;
      text-align: center;
      line-height: 70px;
      .el-form-item {
        margin: 0 !important;
        height: 100%;
        line-height: 70px;
      }
      .el-form-item__content {
        line-height: 70px !important;
      }
    }
  }
}
</style>